package com.laomuji.android.mvvm.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatRadioButton
import com.laomuji.android.mvvm.R
import androidx.core.content.withStyledAttributes


/**
 * 可以自定义图标大小的RadioButton
 * @author laomuji666
 * @since 2024/2/21
 */
class CustomRadioButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    AppCompatRadioButton(context, attrs) {
    private var iconRes = 0
    private var iconWidth = 0
    private var iconHeight = 0
    private var isInitDrawable = false
    private var direction = 0

    init {
        attrs?.let { initAttr(context, it) }
    }

    private fun initAttr(context: Context, attrs: AttributeSet) {
        context.withStyledAttributes(attrs, R.styleable.CustomRadioButton) {
            iconRes = getResourceId(R.styleable.CustomRadioButton_crbIconRes, 0)
            iconWidth = getDimensionPixelSize(R.styleable.CustomRadioButton_crbIconWidth, 0)
            iconHeight = getDimensionPixelSize(R.styleable.CustomRadioButton_crbIconHeight, 0)
            direction = getInt(R.styleable.CustomRadioButton_crbDirection, 0)
        }
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun initDrawable() {
        if (isInitDrawable) {
            return
        }
        isInitDrawable = true
        if (iconRes == 0) {
            return
        }
        val iconDrawable = resources.getDrawable(iconRes)
        iconDrawable.setBounds(0, 0, iconWidth, iconHeight)
        if (direction == 1) {
            setCompoundDrawables(iconDrawable, null, null, null)
        }
        if (direction == 2) {
            setCompoundDrawables(null, iconDrawable, null, null)
        }
        if (direction == 3) {
            setCompoundDrawables(null, null, iconDrawable, null)
        }
        if (direction == 4) {
            setCompoundDrawables(null, null, null, iconDrawable)
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        initDrawable()
    }
}
